package org.skywork.top.core.algorithm.num;

import org.skywork.top.core.algorithm.support.ListNode;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 两数相加
 */
public class no_2 {


    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        List<Integer> list = new ArrayList<>();
        addTwoNumbers2(l1, l2, list, false);
        return node(list);
    }


    public ListNode node(List<Integer> listNode){
        ListNode node = new ListNode(listNode.get(0));
        ListNode next = node;
        for(int i = 1; i < listNode.size(); i++){
            next.next = new ListNode(listNode.get(i));
            next = next.next;
        }
        return node;
    }

    private static void addTwoNumbers2(ListNode l1, ListNode l2, List<Integer> node, boolean add) {
        int num = 0;
        if(l1 == null && l2 == null){
            if(add){
                node.add(1);
            }
            return;
        }
        if(l1 == null){
            num = l2.val;
        }else if(l2 == null){
            num = l1.val;
        }else {
            num = l1.val + l2.val;
        }

        if(add){
            num += 1;
        }
        if(num > 9){
            int single = num % 10;
            node.add(single);
        }else{
            node.add(num);
        }
        addTwoNumbers2(l1 == null ? null : l1.next, l2 == null ? null : l2.next, node, num > 9);
    }


}
